﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data;
using System.Text;
//using System.Windows.Forms;
using VAdvantage.Classes;
using VAdvantage.Common;
using VAdvantage.Grids;
using VAdvantage.DataBase;
using VAdvantage.Utility;
using VAdvantage.Editor;
using VAdvantage.Model;
using System.ComponentModel;

namespace VAdvantage.Framework
{
    /// <summary>
    /// To allow user to set his value prefernce of a control
    /// </summary>
    public partial class ValuePreference : ChildWindow
    {
        #region "Private Variables"

        private Context ctx;
        private int windowNo;
        private int _AD_Client_ID;
        private int _AD_Org_ID;
        private int _AD_User_ID;
        private int _AD_Window_ID;
        private String attribute;
        private String displayAttribute;
        private String value;
        private String displayValue;
        private int displayType;
        private Model.MRole role;


        private bool _chkUser, _chkTenant, _chkWindow, _chkOrg;

        #endregion

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="aWindowNo">window no</param>
        /// <param name="AD_Client_ID">client</param>
        /// <param name="AD_Org_ID">org</param>
        /// <param name="AD_User_ID">user</param>
        /// <param name="AD_Window_ID">window id</param>
        /// <param name="aAttribute">attribute</param>
        /// <param name="aDisplayAttribute">attribute display</param>
        /// <param name="aValue">value</param>
        /// <param name="aDisplayValue">value display</param>
        /// <param name="aDisplayType">display type</param>
        /// <param name="AD_Reference_ID">reference</param>
        public ValuePreference(int aWindowNo, int AD_Client_ID, int AD_Org_ID, int AD_User_ID,
            int AD_Window_ID, String aAttribute, String aDisplayAttribute, String aValue, String aDisplayValue,
            int aDisplayType, int AD_Reference_ID)
        //: base(false, false, false, false, Msg.GetMsg(Envs.GetContext(), "ValuePreference", true))
        {
            base.Title = Msg.GetMsg(Envs.GetContext(), "ValuePreference", true);
            // store values in local variables
            ctx = Utility.Envs.GetContext();
            windowNo = aWindowNo;
            _AD_Client_ID = AD_Client_ID;
            _AD_Org_ID = AD_Org_ID;
            _AD_User_ID = AD_User_ID;
            _AD_Window_ID = AD_Window_ID;
            attribute = aAttribute;
            displayAttribute = aDisplayAttribute;
            value = aValue;
            displayValue = aDisplayValue;
            displayType = aDisplayType;
            //
            role = Model.MRole.GetDefault();

            InitializeComponent();
            // set font
            //InitialFormSetting.SetFont(this);//uncomment it
        }

        private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // display values in label and textbox
            vtxtAttribute.Text = displayAttribute == null ? "" : displayAttribute;
            vlblAttribute.Content = attribute == null ? "" : attribute;
            vtxtSearchKey.Text = displayValue== null ? "": displayValue;
            vlblValue.Content = value;

            // set text according to selected language
            vlblAttributeText.Content = Msg.GetMsg(Envs.GetContext(), "Attribute", true); //Translate(ctx, "Attribute");
            vlblValueText.Content = Msg.GetMsg(Envs.GetContext(), "SearchKey", true); //Translate(ctx, "Value");
            vlblLevelText.Content = Msg.GetMsg(Envs.GetContext(), "ValuePreferenceSetFor", true);
            vchkTenant.Content = Msg.GetMsg(Envs.GetContext(), "Tenant", true); //Translate(ctx, "AD_Client_ID");
            vchkOrg.Content = Msg.GetMsg(Envs.GetContext(), "Org", true); //Translate(ctx, "AD_Org_ID");
            vchkUser.Content = Msg.GetMsg(Envs.GetContext(), "UserContact", true); //Translate(ctx, "AD_User_ID");
            vchkWindow.Content = Msg.GetMsg(Envs.GetContext(), "Window", true); //Translate(ctx, "AD_Window_ID");

            vchkTenant.IsEnabled = false;
            vchkTenant.IsChecked = true;

            vchkUser.IsChecked = true;
            vchkWindow.IsChecked = true;

            //	Can Change Org
            if (!MRole.PREFERENCETYPE_Client.Equals(role.GetPreferenceType()))
            {
                vchkOrg.IsEnabled = false;
                vchkOrg.IsChecked = true;
            }

            //	Can Change User
            if (!(MRole.PREFERENCETYPE_Client.Equals(role.GetPreferenceType())
                || MRole.PREFERENCETYPE_Organization.Equals(role.GetPreferenceType())))
            {
                vchkUser.IsEnabled = false;
                vchkUser.IsChecked = true;
            }
            SetExplanation();
            //vtxtAttribute.Dock = DockStyle.Fill;
            //vtxtSearchKey.Dock = DockStyle.Fill;

            // set width of window
            //if (tblpnlCtrl.Width > this.Width)
            {
                //this.Width = tblpnlCtrl.Width + 5;//uncomment it
            }

            //pnlCtrl.Anchor = ((AnchorStyles)(((AnchorStyles.Top | AnchorStyles.Left) | AnchorStyles.Right)));
            //tblpnlCtrl.Anchor = ((AnchorStyles)(((AnchorStyles.Top | AnchorStyles.Left) | AnchorStyles.Right)));

            //pnlCtrl.Dock = DockStyle.Fill;
            //tblpnlCtrl.Dock = DockStyle.Top;

            //vtxtAttribute.Dock = DockStyle.Fill;//uncomment it
            //vtxtSearchKey.Dock = DockStyle.Fill;//uncomment it

            //MessageBox.Show(this.Location.ToString());
            //this.Location.X = 10;
            //this.StartPosition = FormStartPosition.WindowsDefaultLocation;
        }

        /// <summary>
        /// Adds Preference Menu strip item in combo box context menu
        /// </summary>
        /// <param name="controlName">control to which contextmenu is attached</param>
        /// <param name="menu">context menu strip object</param>
        //public static void AddPreferenceMenuItem(Control control, ContextMenuStrip menu)
        //{
        //    //Type obj = Type.GetType(clsName);
        //    //Control a = (Control)Activator.CreateInstance(obj, true);
        //    // make a tool strip menu item, set its text and image to be shown
        //    ToolStripMenuItem preferenceItem = new ToolStripMenuItem(Common.Msg.GetMsg(Envs.GetContext(),"ValuePreference", true), Properties.Resources.Zoom);

        //    if (control.GetType().ToString().ToLower() == "vframework.Controls.vcombobox")
        //    {
        //        // add click event of menu item
        //        preferenceItem.Click += new EventHandler(((VAdvantage.Controls.VComboBox)control).preferenceItem_Click);
        //    }
        //    // add this menu item in given contextmenu
        //    menu.Items.Add(preferenceItem);
        //}

        /// <summary>
        /// Adds Preference Menu strip item in combo box context menu
        /// </summary>
        /// <param name="handler">event handler</param>
        /// <param name="menu">context menu strip object</param>
        public static void AddPreferenceMenuItem(EventHandler handler, ContextMenuStrip menu)
        {
            //// make a tool strip menu item, set its text and image to be shown
            //ToolStripMenuItem preferenceItem = new ToolStripMenuItem(Msg.GetMsg(Envs.GetContext(), "ValuePreference", true), Properties.Resources.Preference32);
            //if (handler != null)
            //{
            //    // add click event of menu item
            //    preferenceItem.Click += new EventHandler(handler);
            //}
            //// add this menu item in given contextmenu
            menu.AddPreferenceItem();//  .Items.Add(preferenceItem);
        }

        /// <summary>
        /// Opens Value Preference window after setting initial values
        /// </summary>
        /// <param name="field">field</param>
        /// <param name="aValue">value</param>
        /// <returns>valuepreference object</returns>
        public static ValuePreference Start(Grids.GridField field, Object aValue)
        {
            return Start(field, aValue, null);
        }

        /// <summary>
        /// Opens Value Preference window after setting initial values
        /// </summary>
        /// <param name="field">field</param>
        /// <param name="val">value</param>
        /// <param name="dispValue">display value</param>
        /// <returns>valuepreference object</returns>
        public static ValuePreference Start(Grids.GridField field, Object val, String dispValue)
        {
            // check whether field is editable
            if (field == null || !field.IsEditable(false))
            {
                // if field not editable, return null
                return null;
            }

            //  Set Value/DisplayValue
            String aValue = null;
            String aDisplayValue = null;
            // if value exists
            if (val != null)
            {
                // set value
                aValue = val.ToString();
                if (val.GetType() == typeof(bool))
                    aValue = ((Boolean)val) ? "Y" : "N";

                //if (field.GetDisplayType() == DisplayType.YesNo)
                //    aValue = (val.ToString().ToLower().Equals("true")) ? "Y" : "N";
                //else if (field.GetDisplayType() == DisplayType.Date)
                //    aValue = Convert.ToDateTime(val.ToString());

                // set display value
                aDisplayValue = (dispValue == null) ? aValue : dispValue;
            }

            //  Get from field
            //  AD_Window_ID, DisplayAttribute, Attribute, DisplayType, AD_Referenece_ID
            int AD_Window_ID = field.GetAD_Window_ID();
            String aAttribute = field.GetColumnName();
            String aDisplayAttribute = field.GetHeader();
            int aDisplayType = field.GetDisplayType();
            int AD_Reference_ID = 0;
            int winNo = field.GetWindowNo();

            if ("Value".Equals(aAttribute) || "DocumentNo".Equals(aAttribute))
            {
                // No Preference for "Value" or "DocumentNo" attributes
                return null;
            }

            //  Get from GlobalVariable
            //  AD_Client_ID, AD_Org_ID, AD_User_ID
            Ctx contxt = Utility.Envs.GetContext();
            int AD_Client_ID = contxt.GetAD_Client_ID();
            int AD_Org_ID = contxt.GetContextAsInt(winNo, "AD_Org_ID");
            int AD_User_ID = contxt.GetAD_User_ID();

            //  Opens Value Preference window
            ValuePreference vp = new ValuePreference(winNo, AD_Client_ID, AD_Org_ID, AD_User_ID,
                AD_Window_ID, aAttribute, aDisplayAttribute, aValue, aDisplayValue, aDisplayType, AD_Reference_ID);
            // return object
            return vp;
        }

        /// <summary>
        /// Set message text on window
        /// </summary>
        private void SetExplanation()
        {
            /** @todo translation */
            StringBuilder expl = new StringBuilder("For ");
            // set text according to tenant and organization collectively
            if ((bool)vchkTenant.IsChecked && (bool)vchkOrg.IsChecked)
            {
                expl.Append("this Client and Organization");
            }
            else if ((bool)vchkTenant.IsChecked && !(bool)vchkOrg.IsChecked)
            {
                expl.Append("all Organizations of this Client");
            }
            else if (!(bool)vchkTenant.IsChecked && (bool)vchkOrg.IsChecked)
            {
                vchkOrg.IsChecked = false;
                expl.Append("entire System");
            }
            else
                expl.Append("entire System");

            // set text according to user
            if ((bool)vchkUser.IsChecked)
            {
                expl.Append(", this User");
            }
            else
            {
                expl.Append(", all Users");
            }

            // set text according to window
            if ((bool)vchkWindow.IsChecked)
            {
                expl.Append(" and this Window");
            }
            else
            {
                expl.Append(" and all Windows");
            }
            //
            if (Utility.Envs.IsBaseLanguage(ctx, ""))// DataBase.GlobalVariable.IsBaseLanguage())
            {
                vlblMsg.Content = expl.ToString();
            }

            _chkOrg = (bool)vchkOrg.IsChecked;
            _chkUser = (bool)vchkUser.IsChecked;
            _chkWindow = (bool)vchkWindow.IsChecked;
            _chkTenant = (bool)vchkTenant.IsChecked;

        }

        /// <summary>
        /// Get Preference ID
        /// </summary>
        /// <returns>Preference ID if already exists else 0</returns>
        private int GetAD_Preference_ID()
        {
            // make sql query to get preference id
            StringBuilder sql = new StringBuilder("SELECT AD_Preference_ID FROM AD_Preference WHERE ");
            //	Client
            sql.Append("AD_Client_ID=").Append(_chkTenant ? _AD_Client_ID : 0);
            //	Org
            sql.Append(" AND AD_Org_ID=").Append(_chkOrg ? _AD_Org_ID : 0);
            //	Optional User
            if (_chkUser)
                sql.Append(" AND AD_User_ID=").Append(_AD_User_ID);
            else
                sql.Append(" AND AD_User_ID IS NULL");
            //	Optional Window
            if (_chkWindow)
                sql.Append(" AND AD_Window_ID=").Append(_AD_Window_ID);
            else
                sql.Append(" AND AD_Window_ID IS NULL");
            //	Attribute (Key)
            sql.Append(" AND Attribute='").Append(attribute).Append("'");
            //
            int id = 0;
            DataSet ds = DB.ExecuteDataset(sql.ToString(), null, null);
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                // get id
                id = int.Parse(ds.Tables[0].Rows[0][0].ToString());
            }
            if (id < 0)
                id = 0;
            return id;
        }

        /// <summary>
        /// Get Context
        /// </summary>
        /// <returns>string context key name</returns>
        private String GetContextKey()
        {
            if (_chkWindow)
                return "P" + _AD_Window_ID + "|" + attribute;
            else
                return "P|" + attribute;
        }

        /// <summary>
        /// Save preference to database
        /// </summary>
        /// <returns>bool type if saved succefully else false</returns>
        /// 

        public bool Save()
        {
            //	Handle NULL
            if (value == null || value.Length == 0)
            {
                if (DisplayType.IsLookup(displayType))
                    value = "-1";	//	 -1 may cause problems (BPartner - M_DiscountSchema
                else if (DisplayType.IsDate(displayType))
                    value = " ";
                else
                {
                    //ShowMessage.Warn("ValuePreferenceNotInserted", true, "", null);
                    return false;
                }
            }
            //	No Variables (SQL)
            else if (value.IndexOf("@") != -1)
            {
                ////ShowMessage.Warn("ValuePreferenceNotInserted", true, "", null);
                return false;
            }

            bool success = false;
            // get preference id
            int AD_Preference_ID = GetAD_Preference_ID();
            MPreference pref = new MPreference(ctx, AD_Preference_ID, null);
            // if preference id=0
            if (AD_Preference_ID == 0)
            {
                // if inserting a new record, then set initial values
                // set client id
                int Client_ID = _chkTenant ? _AD_Client_ID : 0;
                // set organization id
                int Org_ID = _chkOrg ? _AD_Org_ID : 0;
                pref.SetClientOrg(Client_ID, Org_ID);
                // set window id
                if (_chkWindow)
                    pref.SetAD_Window_ID(_AD_Window_ID);
                // set user id
                if (_chkUser)
                    pref.SetAD_User_ID(_AD_User_ID);
                // set attribute(columnname)
                pref.SetAttribute(attribute);
            }
            // set value of attribute
            pref.SetValue(value);
            // save the record
            success = pref.Save();
            // if record saved successfully
            if (success)
            {
                // set into context the value of attribute
                ctx.SetContext(GetContextKey(), value);
                // show success message
                //ShowMessage.Info("ValuePreferenceInserted", true, "", null);
            }
            else
            {
                //ShowMessage.Warn("ValuePreferenceNotInserted", true, "", null);
               
            }
            return success;
        }

        /// <summary>
        /// Delete the existing preference
        /// </summary>
        /// <returns>bool type true if record deleted succesfully else false</returns>
        public bool Delete()
        {
            //log.info("");
            bool success = false;
            // get preference id
            int AD_Preference_ID = GetAD_Preference_ID();
            // if preference exists
            if (AD_Preference_ID > 0)
            {
                MPreference pref = new MPreference(ctx, AD_Preference_ID, null);
                // delete the preference
                success = pref.Delete(true);
                // if deleted succesfully set the value to null in context
                if (success)
                    ctx.SetContext(GetContextKey(), (String)null);
            }
            return success;
        }

        private void ibtnCancel_Click(object sender, RoutedEventArgs e)
        {
            // close window
            this.DialogResult = false;
        }
                
        private void ibtnOK_Click(object sender, RoutedEventArgs e)
        {
            // save record

            BackgroundWorker bgw = new BackgroundWorker();

            bgw.DoWork += (sd, ed) =>
            {
                ed.Result = Save();
            };
            bgw.RunWorkerCompleted += (sc, ec) =>
            {
                if (ec.Result != null && (bool)ec.Result)
                {
                    ShowMessage.Info("ValuePreferenceInserted", true, "", null);
                }
                else
                {
                    ShowMessage.Warn("ValuePreferenceNotInserted", true, "", null);
                }
                this.Cursor = Cursors.Arrow;
                bgw = null;
                this.DialogResult = true;
            };
            bgw.RunWorkerAsync();
            this.Cursor = Cursors.Wait;
        }

      private void ibtnDelete_Click(object sender, RoutedEventArgs e)
        {
            // if record deleted successfully, show message

            BackgroundWorker bgw = new BackgroundWorker();

            bgw.DoWork += (sd, ed) =>
                {
                    ed.Result = Delete();
                };
            bgw.RunWorkerCompleted += (sc, ec) =>
                {
                    if (ec.Result != null && (bool)ec.Result)
                    {
                        ShowMessage.Info("ValuePreferenceDeleted", true, "", null);
                    }
                    else
                    {
                        ShowMessage.Warn("ValuePreferenceNotFound", true, "", null);
                    }
                    this.Cursor = Cursors.Arrow;
                    bgw = null;
                    this.DialogResult = true;
                };
            bgw.RunWorkerAsync();
            this.Cursor = Cursors.Wait;
            // close this window
        }

      private void vchk_CheckedChanged(object sender, RoutedEventArgs e)
        {
            // set message text on every check changed of any checkbox
            SetExplanation();
        }

    
    }
}

